/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.vrangogym.auth;

import edu.chl.vrangogym.persistence.entities.User;
import edu.chl.vrangogym.persistence.entities.enums.Permissions;
import java.io.IOException;
import java.security.Permission;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * An Utility Bean that provides methods for authorization.
 * @author Anders
 */
@ManagedBean(name = "Auth")
@ApplicationScoped
public class AuthUtilityBean {

    /** Creates a new instance of AuthUtilityBean */
    public AuthUtilityBean() {
        
    }
    
    /**
     * Method for determining if user is logged in.
     * @return Returns true if user is logged in and false if user is not logged in.
     */
    public boolean isLoggedIn() {
        return FacesContext.getCurrentInstance().getExternalContext()
                    .getSessionMap().get("Auth.user") != null;
    }
    
    /**
     * Method for determining if user is Admin.
     * @return Returns true if user is logged in and is admin, 
     * and returns false otherwise.
     */
    public boolean isAdmin() {
        if(isLoggedIn()) {
            if(((User) FacesContext.getCurrentInstance().getExternalContext()
                    .getSessionMap().get("Auth.user"))
                    .getPermissions() == Permissions.ADMIN) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Logs out a user by invalidating the session.
     * @return Returns the string "onLogout" which can be used in navigation
     */
    public void logout() {
        ((HttpSession) FacesContext.getCurrentInstance().getExternalContext()
                .getSession(false)).invalidate();
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("/vrangogym-web/index.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(AuthUtilityBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
